﻿using Magicodes.ExporterAndImporter.Core.Extension;
using Mapster;
using NetTaste;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using Org.BouncyCastle.Asn1.X509.Qualified;
using Radius.NET.Application;
using Radius.NET.Interface.Kingdee.Attributes;
using System.Globalization;
using System.Reflection;

namespace Admin.NET.Interface.Kingdee.Util.Extension;

/// <summary>
/// 转换扩展类
/// </summary>
public static partial class Extensions
{
    #region Class属性字段转为String[]
    /// <summary>
    /// Class属性字段转为String[]
    /// </summary>
    /// <returns></returns>
    public static string[] ToKingdeeFieldKeys(this object obj)
    {
        try
        {
            List<string> fileds = new();
            var pros = obj.GetType().GetProperties();
            foreach (var item in pros)
            {
                var attr = item.GetAttribute<KingdeeColumnAttribute>();
                if(attr is null)
                {
                    fileds.Add(item.Name);
                }
                else
                {
                    fileds.Add(attr.Name);
                }
            }
            return fileds.ToArray();
        }
        catch
        {
            return new List<string>().ToArray();
        }
    }

    #endregion

    /// <summary>
    /// 根据数组中元素获取泛类中数组下标元素
    /// </summary>
    /// <param name="list">数据源</param>
    /// <param name="source">目标数组</param>
    /// <param name="filed">查询元素</param>
    /// <returns></returns>
    public static Object ItemIndexOf(this List<object> list, string[] source, string filed)
    {
        return list[Array.IndexOf(source, filed)];
    }

    public static List<T> KingdeeToList<T>(this List<List<object>> list)
    {
        List<object> result = new List<object>();
        foreach (var item in list)
        {
            Type t = typeof(T);
            object obj = Activator.CreateInstance(t)!;
            string[] fileds = obj.ToKingdeeFieldKeys();
            foreach (var fieldInfo in typeof(T).GetProperties())
            {
                var attr = fieldInfo.GetAttribute<KingdeeColumnAttribute>();

                var val = item.ItemIndexOf(fileds, attr is null ? fieldInfo.Name.Replace("__", ".") : attr.Name);
                var pro = t.GetProperty(fieldInfo.Name);
                if (fieldInfo.PropertyType == typeof(DateTime) || fieldInfo.PropertyType == typeof(DateTime))
                {
                    pro.SetValue(obj, Convert.ChangeType(val is null ? DateTime.MinValue : val, fieldInfo.PropertyType));
                }
                else
                {
                    pro.SetValue(obj, Convert.ChangeType(val, fieldInfo.PropertyType));
                }
            }
            result.Add(obj);
        }
        return result.Adapt<List<T>>();
    }
}
